package com.anysoft.home.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.base.BaseFragment;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StringUtils;
import com.anysoft.view.CustomMarqueeTextView;
import com.anysoft.view.HProgressBarLoading;
import com.anysoft.web.SelectWarmPromptActivity;
import com.anysoft.web.WisdomActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.anysoft.HostConstant.HOST_WEB_URL_HEADER;
import static com.anysoft.MentorConst.APP_CACAHE_DIRNAME;

/**
 * Created by wwq on 2017/3/17.
 *  智慧页面(现已砍掉)
 */

public class WisdomWebviewTab extends BaseFragment {

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.cmtv_title)
    CustomMarqueeTextView cmtvTitle;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.wv)
    WebView mWebView;
    @BindView(R.id.iv_leftButton)
    ImageView ivLeftButton;
    @BindView(R.id.tv_item_web_error)
    TextView tvItemWebError;
    @BindView(R.id.ll_item_web_error)
    LinearLayout llItemWebError;

    @BindView(R.id.top_progress)
    HProgressBarLoading top_progress;

    private BaseActivity mActivity;
    public String loadUrl;
    public Intent mIntent = new Intent();

    private boolean isLoadError = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wisdom_webview, container, false);
        ButterKnife.bind(this, view);

        leftButton.setVisibility(View.GONE);
        ivLeftButton.setVisibility(View.GONE);
        title.setText("智慧");

        mActivity = (BaseActivity) getActivity();

        initUrl("wisdom", HttpUtils.getCommonParams2StringByWeb(mActivity) + "&cusNo=" + mActivity.getFundCustomerNo()
                + "&token=" + mActivity.getToken());

        return view;
    }

    public void initUrl(String action, String param) {
        loadUrl = HOST_WEB_URL_HEADER + action + ".html?isFromApp=true&" + param;
        MentorLogger.Log("WisdomWebviewTab", "loadUrl=" + loadUrl);
        initView(loadUrl);
    }

    private boolean isFinishGo;

    public void initView(String url) {
        isFinishGo = false;

        MentorLogger.Log("WisdomWebviewTab", "loadUrl---" + loadUrl);

        mWebView.getSettings().setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= 21) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        mWebView.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = mActivity.getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        MentorLogger.Log("WisdomWebviewTab", "cacheDirPath=" + cacheDirPath);
        //设置数据库缓存路径
        mWebView.getSettings().setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        mWebView.getSettings().setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        mWebView.getSettings().setAppCacheEnabled(true);

//        //TODO 关闭万恶的缓存，效果未知
//        mWebView.getSettings().setJavaScriptEnabled(true);
//        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //关闭webview中缓存
//        // 开启 DOM storage API 功能
//        mWebView.getSettings().setDomStorageEnabled(false);
//        //开启 database storage API 功能
//        mWebView.getSettings().setDatabaseEnabled(false);
//        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
//        MentorLogger.Log(TAG, "cacheDirPath=" + cacheDirPath);
//        //设置数据库缓存路径
//        mWebView.getSettings().setDatabasePath(cacheDirPath);
//        //设置  Application Caches 缓存目录
//        mWebView.getSettings().setAppCachePath(cacheDirPath);
//        //开启 Application Caches 功能 false--关闭，即，H5的缓存无法使用
//        mWebView.getSettings().setAppCacheEnabled(false);
//        mWebView.clearCache(true);
//        mWebView.clearHistory();
//        mWebView.clearFormData();
//        //TODO 清楚cookie，效果未知
//        CookieManager.getInstance().removeAllCookie();
//        CookieManager.getInstance().removeSessionCookie();

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onLoadResource(WebView view, String url) {
//                MentorLogger.Log(TAG, "onLoadResource url=" + url);
                super.onLoadResource(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webview, String url) {
                MentorLogger.Log("WisdomWebviewTab", "intercept url=" + url);
                onshouldOverrideUrlLoadingCallBack(webview, url);
                return true;
            }

//            @Override
//            public boolean shouldOverrideUrlLoading(WebView webview, String url) {
//                MentorLogger.Log(TAG, "intercept url=" + url);
//                webview.loadUrl(url);
//                return true;
//            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                MentorLogger.Log("WisdomWebviewTab", "onPageStarted");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                isFinishGo = true;

                String title = view.getTitle();
                MentorLogger.Log("WisdomWebviewTab", "onPageFinished WebView title=" + title);
                if (!isLoadError) {
                    mWebView.setVisibility(View.VISIBLE);
                    llItemWebError.setVisibility(View.GONE);
                } else {
                    isLoadError = false;
                    mWebView.setVisibility(View.GONE);
                    llItemWebError.setVisibility(View.VISIBLE);
                }


            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                MentorLogger.Log("WisdomWebviewTab", "onReceivedError");
            }

            //WebView不能加载https,需要重写这个方法
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                MentorLogger.Log("WisdomWebviewTab", "onReceivedSslError");
                handler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                MentorLogger.Log("WisdomWebviewTab", "onReceivedError");
//                mActivity.showToast("onReceivedError");
                isLoadError = true;
                mWebView.setVisibility(View.GONE);
                llItemWebError.setVisibility(View.VISIBLE);
                super.onReceivedError(view, request, error);
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                MentorLogger.Log("WisdomWebviewTab", "onReceivedHttpError");
                MentorLogger.Log("WisdomWebviewTab", errorResponse.getEncoding()
                        + "---" + errorResponse.getMimeType()
                        + "---" + errorResponse.getStatusCode()
                );

                if ("404".equals(errorResponse.getStatusCode() + "")) {
                    if (isFinishGo) {
                        isLoadError = true;
                    }
                    mWebView.setVisibility(View.GONE);
                    llItemWebError.setVisibility(View.VISIBLE);
                }
                super.onReceivedHttpError(view, request, errorResponse);
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                top_progress.setCurProgress(newProgress);
            }
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                MentorLogger.Log("WisdomWebviewTab", "onJsAlert:" + message);
//                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                result.confirm();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                MentorLogger.Log("WisdomWebviewTab", "onJsConfirm:" + message);
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                MentorLogger.Log("WisdomWebviewTab", "onJsPrompt:" + url);
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });

        class JavaScriptObject {
            @JavascriptInterface
            public void t_buy_apply_bank() {
            }

            @JavascriptInterface
            public void t_buy_apply_482002() {
            }

            @JavascriptInterface
            public void t_buy_confirm() {
            }

            @JavascriptInterface
            public void t_buy_result() {
            }

            @JavascriptInterface
            public void t_redeem_apply_bank() {
            }

            @JavascriptInterface
            public void t_redeem_apply_482002() {
            }

            @JavascriptInterface
            public void t_redeem_confirm() {
            }

            @JavascriptInterface
            public void t_redeem_result() {
            }

            @JavascriptInterface
            public void t_transfer_apply() {
            }

            @JavascriptInterface
            public void t_transfer_confirm() {
            }

            @JavascriptInterface
            public void t_transfer_result() {
            }
        }
        //设置本地调用对象及其接口
        mWebView.addJavascriptInterface(new JavaScriptObject(), "js_invoke");

        mWebView.loadUrl(url);
    }


    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        MentorLogger.Log("WisdomWebviewTab", "url=" + url);
        if (url.contains("prompt.html")) {
            mIntent.setClass(mActivity, SelectWarmPromptActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains("recommendScheme.html")) {
            if (mActivity.mentorApplication.needLogin()) {
                ActivityUtils.gotoLogin(mActivity,mActivity.hasUser(), false,
                        mActivity.findUserId());
            } else {
                if (StringUtils.isNullOrEmpty(mActivity.getUserLevel())) {//未做评测
                    mActivity.startRiskActivity(null);
                } else {
                    mActivity.startActivity(new Intent().setClass(mActivity, WisdomActivity.class));
                }
            }
        } else {
            webview.loadUrl(url);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @OnClick(R.id.tv_item_web_error)
    public void onClick() {
        mWebView.setVisibility(View.GONE);
        llItemWebError.setVisibility(View.GONE);
        initView(loadUrl);
    }

}
